<!-- 支持编辑的table -->
<template>
  <div class="c-editTable">
  <Table :data="editValue || []" :columns="calcColumns" v-bind="tableConfig">
    <template slot-scope="{ row, index }" slot="operation">
      <Button v-if="!readOnly && (!maxLength || editValue.length < maxLength) && showAddBtn"
        style="margin-right: 12px;" size="small" @click="addLine(index)">+</Button>
      <Poptip v-if="!readOnly && showDelBtn && !row._readOnly && index !=0" confirm title="是否删除？" transfer
        @on-ok="removeLine(index)">
        <Button class="btn-del" size="small">-</Button>
      </Poptip>
    </template>
    <template slot-scope="{ row, index }" slot="slotCustom1">
      <slot name="custom1" :row="row" :index="index"></slot>
    </template>
  </Table>
  <p v-if="showAddBtn && !readOnly && (!editValue || !editValue.length)" class="addline">
    <Button @click="addFirstLine" size="small">+</Button>
  </p>
</div>
</template>

<script>
import lodash from 'lodash'

let typeObj = { String: 'text',Double: 'number',Integer: 'number',Boolean: 'check',DateTime: 'datetime'}
export default {
  name: "cfgEditTable",
  data() {
    return {
      showAddBtn: false,
      showDelBtn: false,
      editValue: []
    }
  },
  methods: {
    addLine(index) {
      let newItem = typeof this.addTpl === 'function' ? this.addTpl(this.editValue.length+1) : {...this.addTpl}
      this.editValue.splice(index+1,0, newItem)
      this.change()
    },
    addFirstLine() {
      let newItem = typeof this.addTpl === 'function' ? this.addTpl(1) : {...this.addTpl}
      this.editValue.push(newItem)
      this.change()
      // this.$forceUpdate()
    },
    removeLine(index) {
      this.editValue.splice(index,1)
      this.change()
    },
    change() {
      this.$emit('change', this.editValue)
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  watch: {
    value: {
      handler(val) {
        this.editValue = this.tools.lodash.isArray(val) ? val : []
        // let filter = val.filter(item => !item) 
        // if (filter.length) {
        //   debugger
        // }
      }, immediate: true
    }
  },
  props: {
    // 支持通过v-model实现双向绑定
    value: {
      default() {
        return []
      }
    },
    /* 在table的原有columns基础上，增加了字段elementName和props，则使用动态element来渲染，结构如下：
      [{
        key: 'trigger',
        title: 'trigger',
        width: 100,
        elementName: 'fieldCell', // 可编辑的动态组件，组件需要支持：props中有value，并且数据变化时触发change事件
        props: { config: { type: 'select', options: []} } // 可编辑组件的属性
      }]
    */
    columns: {
      default() {
        return []
      }
    },
    // 新增一行时，默认的formData数据，如：{ name: 'xx', refModel: {} }
    addTpl: {
      default() {
        return {}
      }
    },
    // iview的table组件相关的props
    tableConfig: {
      default() {
        return {}
      }
    },
    // 是否在第一列显示序号
    showNum: {
      default: true
    },
    maxLength: {
      default() {
        return null
      }
    },
    readOnly: {
      default: false
    }
  },
  computed: {
    calcColumns() {
      let columns = lodash.cloneDeep(this.columns)
      let res = columns.map(item => {
        if(item.render) {
          // item.render = item.render.call(this)
        }
        else if (!item.render && item.elementName) {
          item.render = (h, params) => {
            let props = {...item.props}
            let config = props.config || {}

            if (item.dynamicType) {
              let fieldType = typeObj[params.row[item.dynamicType] || 'String'] || 'text'
              config.type = fieldType
            }
            return h(item.elementName, {
              props: {
                ...props,
                config: {
                  ...config,
                  disabled: this.readOnly ? true : !!config.disabled
                },
                value: lodash.get(params.row, item.key),
                key: this.tools.uuid()
              },
              class: 'dyEle',
              on: {
                change: val => {
                  let newItem = this.editValue[params.index]
                  lodash.set(newItem, item.key, val)
                  // newItem[item.key] = val
                  // item.changeDeleteItem && (newItem[item.changeDeleteItem] = null)
                  this.editValue.splice(params.index, 1, newItem)
                  this.change()
                  //修改的单元格信息
                  this.$emit('changeCell',{index:params.index,key:item.key,val})
                }
              }
            })
          }
        }
        if (item.slot === 'operation') {
          item.title = this.lang.operation
          item.buttons = item.buttons || ['add', 'delete']
          item.width = item.width || 65
          item.className = 'operationWp'
          this.showAddBtn = item.buttons.includes('add')
          this.showDelBtn = item.buttons.includes('delete')
        }
        return item
      })
      this.showNum && (res.unshift({
        width: 56,
        title: this.lang.orderNo,
        type: 'index',
        align: 'center',
        className: 'orderNowp'
      }))
      return res;
    },
    lang() {
      return {
        "en-US": {
          operation: 'operation',
          orderNo: 'orderNo',
          newLine: 'add line',
        },
        "zh-CN": {
          operation: '操作',
          orderNo: '序号',
          newLine: '新增一行',
        },
      }[this.G_Locale]
    },
  },
}
</script>

<style lang="less" scoped>
.c-editTable {
  padding: 6px 0;
  width: 100%;
  /deep/ .ivu-table {
    &:before {
      display: none;
    }
    .ivu-table-header thead tr th {
      text-align: center;
      font-weight: normal;
      background-color: #f7f7f7;
      &.operationWp {
        text-align: left;
        padding: 0;
      }
      &.orderNowp .ivu-table-cell {
        padding: 0;
      }
    }
    td {
      height: 40px;
      border-bottom: none;
      &.orderNowp .ivu-table-cell {
        width: 50px;
        height: 32px;
        line-height: 32px;
        padding: 0;
        margin-right: 6px;
        border-radius: 4px;
        background-color: #f7f7f7;
      }
    }
    .ivu-table-cell {
      padding: 0;
    }
    .ivu-table-cell:has(.dyEle) {
      padding-left: 0;
      padding-right: 8px;
    }
  }
  .addline {
    position: relative;
    top: -28px;
    left: -55px;
    text-align: right;
  }
}
</style>
